package com.example.stock.service.impl;

import com.example.stock.entity.User;
import com.example.stock.entity.UserToken;
import com.example.stock.service.UserService;
import com.example.stock.util.LoginUtil;
import com.example.stock.util.NumberUtil;
import com.example.stock.util.SystemUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Log4j2
@Service
public class UserServiceImpl implements UserService {

    private final Map<Long, User> loginUser = new HashMap<>();

    private final Map<String, UserToken> userTokens = new HashMap<>();

    @Value("${user.loginName}")
    private String mockUsername;

    @Value("${user.password}")
    private String mockPassword;

    private User mockUser() {
        User user = new User();
        user.setUserId(1L);
        user.setNickName("管理员");
        user.setLoginName(mockUsername);
        user.setLockedFlag((byte) 0);
        user.setIsDeleted((byte) 0);
        return user;
    }

    @Override
    public String login(String loginName, String passwordMD5) {
        if (!(loginName.equals(mockUsername) && passwordMD5.equals(mockPassword))) {
            return null;
        }

        // 模拟用户已经登陆
        User user = mockUser();
        loginUser.put(user.getUserId(), user);

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);//过期时间 48 小时

        //登录后即执行修改token的操作
        String token = getNewToken(System.currentTimeMillis() + "", user.getUserId());
        UserToken userToken = new UserToken();
        userToken.setUserId(user.getUserId());
        userToken.setLoginName(user.getLoginName());
        userToken.setExpireTime(expireTime);
        userToken.setToken(token);
        userTokens.put(token,userToken);

        return token;
    }

    /**
     * 获取token值
     *
     * @param timeStr
     * @param userId
     * @return
     */
    private String getNewToken(String timeStr, Long userId) {
        String src = timeStr + userId + NumberUtil.genRandomNum(4);
        return SystemUtil.genToken(src);
    }

    @Override
    public Boolean logout(Long userId) {
        return null;
    }

    @Override
    public UserToken selectUserTokenByToken(String token) {
        return userTokens.get(token);
    }

    @Override
    public User selectUserByPrimaryKey(Long userId) {
        return loginUser.get(userId);
    }

    @Value("${spring.profiles.active}")
    private String env;

    @Override
    public Boolean isLogin() {
        if (env.equals("dev")) {
            return true;
        }
        return LoginUtil.getLoginUser() != null;
    }
}